import 'package:star_author/utils/common_util/date_util.dart';

class BackflowModelUtil {
  ///获取中拍订单状态
  ///4种状态：closed initial  [paid finished]
  ///一般超时就用closed判断
  ///[paid finished] 一般不会出现paid。一般支付完就直接finished了；除非数据异常。不过为了保证前端显示正常。把这两个都放在一起判断。
  ///
  /// 返回状态：
  /// 已关闭 null
  /// 待付款 from_bidder_need_paid
  /// 待处理 from_bidder_need_handle
  /// 寄售中 from_bidder_offline_saling
  /// 待收货 from_bidder_handled_backing
  /// 已完成 from_bidder_completed
  ///
  /// 显示状态：
  /// 待付款 initial
  /// 待处理 needhandle
  /// 寄售中 onsale
  /// 寄售中-已锁定 sold
  /// 待收货 back
  /// 已完成 finished
  /// 已关闭 pay_expired

  static String getStatus(Map map) {
    String? combine_status = map['combine_status'];

    //已关闭
    if (combine_status == null) {
      return 'pay_expired';
    }

    if (combine_status == 'from_bidder_need_paid') {
      return 'initial';
    }

    if (combine_status == 'from_bidder_need_handle') {
      return 'needhandle';
    }

    if (combine_status == 'from_bidder_offline_saling') {
      int? stock = map['klone_backflow']['stock'] ?? 0;

      if (stock! > 0) {
        return 'onsale';
      } else {
        return 'sold';
      }
    }

    if (combine_status == 'from_bidder_handled_backing') {
      return 'back';
    }

    if (combine_status == 'from_bidder_completed') {
      return 'finished';
    }

    return '';
  }

  static bool checkIsSold(String status, int stock) {
    return status == 'onsale' && stock == 0;
  }

  static bool isExpired(item) {
    String expired_evaluated_at = item['expired_evaluated_at'] ?? '';
    Duration? countDownVal =
        DateUtil.getDateTime(expired_evaluated_at)?.difference(DateTime.now());

    bool isExpired = countDownVal == null || countDownVal.inSeconds < 0;

    return isExpired;
  }

  static void correctionStatus(item) {
    bool tender_full =
        item['already_tenders_count'] == item['need_tenders_count'];
    item['tender_full'] = tender_full;

    if (checkIsSold(item['status'], item['stock'])) {
      // 只有本人的回流单会有winning_order字段，非本人的回流单该字段为null
      Map winning_order = item['winning_order'] ?? {};
      if (winning_order['status'] != 'initial') {
        item['status'] = 'sold';
      } else {
        item['status'] = 'wait_pay';
      }
    }
  }
}
